<?php
namespace app\api\controller\deerhome\user;
use think\Db;
use app\api\controller\deerhome\user\Base;

use app\admin\model\deerhome\SmsLog as SmsLogModel;
use app\admin\model\deerhome\User as UserModel;

class Login extends Base
{

    protected $noNeedLogin = ['*']; 
	public $hash="Ta1#o%dgiP4%kpb";

    public function info()
    {
		$gzh_code = $this->request->param('gzh_code','','trim');

		$data=[];
		$data['logo']=$this->getXcxLogo();
		$data['wechat_logo']=$this->fixImg('/assets/addons/deerhome/img/logo_wechat.png');
		$data['wechat_appid']=configDeer("gh_app_id");
		$data['title']=$this->getXcxName();
		$data['article1']=Db::name("deerhome_article")->where("cate",1)->where("name","隐私政策")->value("id");
		$data['article2']=Db::name("deerhome_article")->where("cate",1)->where("name","用户协议")->value("id");

		$data['token']='';
		$data['token_msg']='';
		$data['user_face']='';
		$data['user_nickname']='';
		$data['user_gzh_openid']='';
		$data['user_gzh_hash']='';

		//如果是公众号带code进入
		if($gzh_code){
			try{
				$config = $this->getWeixinGzhConfig();
				$wechat = \WeChat\Oauth::instance($config);
				$res=$wechat->getOauthAccessToken($gzh_code);
				if(isset($res['errcode'])){
					if($res['errcode']!=0){
						throw new \Exception($res['errmsg']);
					}
				}
				$user=UserModel::where('wxid_gzh',$res['openid'])->find();
				if(!$user){
					$userInfo=$wechat->getUserInfo($res['access_token'],$res['openid']);
					$data['user_face']=$userInfo['headimgurl'];
					$data['user_nickname']=$userInfo['nickname'];
					$data['user_gzh_openid']=$res['openid'];
					$data['user_gzh_hash']=md5($this->hash.$res['openid']);
					throw new \Exception('未绑定公众号');
				}
				$data['token']=md5($user['token'].time());
				$user->token=$data['token'];
				$user->last_time=date("Y-m-d H:i:s");
				$user->save();
			}catch(\Exception $e){
				$data['token_msg']=$e->getMessage();
			}
		}

		$this->ok($data);
	}
    public function index()
    {
		$way = $this->request->param('way','page_wxtel','trim');
		$tel = $this->request->param('tel','','trim');
		$openid = $this->request->param('openid','','trim');
		$hash = $this->request->param('hash','','trim');
		$code = $this->request->param('code','','trim');
		$gzh_hash = $this->request->param('gzh_hash','','trim');
		$gzh_openid = $this->request->param('gzh_openid','','trim');
		$face = $this->request->param('face','','trim');
		$name = $this->request->param('name','','trim');
		$token = md5($this->hash.time().$tel);
		if(!preg_match("/^1\d{10}$/", $tel)){
			$this->err('手机号格式不正确');
		}
		if($code=="" && $hash=="" && $openid==""){
			$this->err('参数错误');
		}
		if(!in_array($way,['page_wxtel','page_sms'])){
			$this->err('不支持的登录方式');
		}
		$userInfo=null;
		$userIsExit = null;
		if($this->_deviceType=="wxapp"){
			if(!preg_match("/^[a-z0-9_-]{10,40}$/i", $openid)){
				$this->err('openid格式不正确');
			}
			if(md5($this->hash.$tel)!=$hash){
				$this->err('非法操作，请关闭页面重试');
			}
			$userIsExit = UserModel::where('utel',$tel)->find();
			if($userIsExit){
				UserModel::where('wxid',$openid)->where('id','<>',$userIsExit->id)->update([
					'wxid'=>'anonymous_'.$openid
				]);
				if(!$userIsExit['wxid'] || $userIsExit['wxid']!=$openid){
					$userIsExit->wxid=$openid;
					$userIsExit->save();
				}
			}else{
				$userIsExit = UserModel::where('wxid',$openid)->find();
			}
		}else{
			//验证码登录
			if(!(new SmsLogModel)->checkYzm($tel,$code)){
				$this->err('验证码错误或已过期');
			}
			$userIsExit = UserModel::where('utel',$tel)->find();
			//如果是公众号进入
			if($gzh_hash && $gzh_openid){
				$gzh_hash_check=md5($this->hash.$gzh_openid);
				if($gzh_hash_check!=$gzh_hash){
					$this->err('非法操作，请关闭页面重试');
				}
			}
		}
		
		if($userIsExit){
			$map=[];
			$map['reg_ip'] = $this->request->ip() ;
			$map['token'] = $token ;
			$map['last_time'] = \date('Y-m-d H:i:s');
			if($userIsExit['utel']==""){
				$map['utel'] = $tel ;
			}
			if($gzh_hash && $gzh_openid){
				$map['uname'] = $name;
				$map['face_image'] = $face;
				$map['wxid_gzh'] = $gzh_openid;
				if($userIsExit['uname']!='微信用户'){
					unset($map['uname']);
				}
				if($userIsExit['face_image']!=$this->fixImg("/assets/addons/deerhome/img/defalut_face.png")){
					unset($map['face_image']);
				}
			}
			
			UserModel::where('id',$userIsExit['id'])->update($map);
		}else{
			$addArr=[
				'utel'=>$tel
				,'uname'=>$name?$name:'微信用户'
				,'face_image'=>$face?$face:$this->fixImg("/assets/addons/deerhome/img/defalut_face.png")
				,'token'=>$token
				,'wxid'=>$openid
				,'reg_ip'=>$this->request->ip()
				,'regtime'=>\date('Y-m-d H:i:s')
				,'last_time'=>\date('Y-m-d H:i:s')
			];
			if($gzh_hash && $gzh_openid){
				$addArr['wxid_gzh']=$gzh_openid;
			}
			UserModel::insertGetId($addArr);
		}
        
		$data = [
			'token'=>$token
		];
		$this->ok($data);
    }
	public function wxbd(){
		$code=$this->request->param('code','','trim');
		$wxid=$this->request->param('wxid','','trim');
		$res=[];
		try{
			$config = $this->getWeixinConfig();
			$mini = \WeMini\Crypt::instance($config);
			$res=$mini->session($code);
			if(isset($res['errcode'])){
				if($res['errcode']!=0){
					throw new \Exception($res['errmsg']);
				}
			}
		}catch(\Exception $e){
			$this->err("小程序配置错误：".$e->getMessage(),1);
		}
		$isExit=false;
		$userDatas = Db::name('deerhome_user')->where('wxid',$res['openid'])->order('id asc')->select();
		if(count($userDatas)==1){
			$isExit=$userDatas[0];
		}
		if(count($userDatas)>1){
			foreach($userDatas as $user){
				if(strlen($user['utel'])>=11){
					$isExit=$user;
				}else{
					Db::name("deerhome_user")->where("id",$user['id'])->update(['wxid'=>'anonymous_'.$res['openid']]);
				}
			}
			if(!$isExit){
				$isExit=$userDatas[0];
			}
		}
		if(!$isExit){
			$agent_lev1_uid=0;
			$agent_lev2_uid=0;

			//如果是分享进入
			if($wxid){
				$agent=Db::name("deerhome_user")->field("id,agent_lev1_uid")->where("wxid",$wxid)->find();
				if($agent){
					$agent_lev1_uid=$agent['id'];
					$agent_lev2_uid=$agent['agent_lev1_uid'];
				}
			}

			$add=Db::name("deerhome_user")->insertGetId([
				'uname'=>"微信用户"
				,'face_image'=>$this->fixImg("/assets/addons/deerhome/img/defalut_face.png")
				,'wxid'=>$res['openid']
				,'reg_ip'=>$this->request->ip()
				,'regtime'=>\date('Y-m-d H:i:s')
				,'last_time'=>\date('Y-m-d H:i:s')
				,'agent_lev1_uid'=>$agent_lev1_uid
				,'agent_lev2_uid'=>$agent_lev2_uid
			]);
			//自动升级推广人等级
			try{
				\Tools\UserAndAgentLev::actionAgentById($agent_lev1_uid);
			}catch(\Exception $e){
			}
		}else{
			Db::name("deerhome_user")->where("id",$isExit['id'])->update(['last_time'=>date("Y-m-d H:i:s")]);
		}
		$this->ok(["openid"=>$res['openid']]);
	}
	/**
	 * 微信手机号快捷登录
	*/
	public function bywxtel(){
		$code=$this->request->param('code','','trim');
		$encryptedData=$this->request->param('encryptedData','','trim');
		$iv=$this->request->param('iv','','trim');
		$res=[];
		try{
			$config = $this->getWeixinConfig();
			$mini = \WeMini\Crypt::instance($config);
			$res=$mini->getPhoneNumber($code);
			if($res['errcode']!=0){
				throw new \Exception($res['errmsg']);
			}
		}catch(\Exception $e){
			$this->err($e->getMessage());
		}
		$data=[];
		$data['tel']=$res['phone_info']['purePhoneNumber'];
		$data['hash']=md5($this->hash.$data['tel']);;
		$this->ok($data);
	}
	public function getJsSign(){
		$url=$this->request->param('url','','trim');
		$jsApiList=$this->request->param('api',null,'trim');
		if($jsApiList){
			$jsApiList=explode(",",$jsApiList);
		}else{
			$jsApiList=['updateAppMessageShareData', 'updateTimelineShareData','chooseWXPay'];
		}
		$res=[];
		try{
			$config = $this->getWeixinGzhConfig();
			$wechat = \WeChat\Script::instance($config);
			$res=$wechat->getJsSign($url,null,null,$jsApiList);
		}catch(\Exception $e){
			$this->err($e->getMessage());
		}
		$this->ok($res);
	}
}
